#include "Sqlite.h"

// 通用回调：判断记录是否存在
static int callback_exists(void *arg, int argc, char **argv, char **azColName) {
    *(int *)arg = 1;  // 存在记录
    return 0;
}

// 初始化数据库
sqlite3* Sqlite3_Init() {
    sqlite3 *db;
    int rc = sqlite3_open(DB_NAME, &db);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "无法打开数据库: %s\n", sqlite3_errmsg(db));
        return NULL;
    }

    // 创建在线客户端表
    char *sql_clients = "CREATE TABLE IF NOT EXISTS clients ("
                        "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                        "sock_fd INTEGER UNIQUE,"
                        "name TEXT);";
    char *errmsg;
    rc = sqlite3_exec(db, sql_clients, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "创建 clients 表失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        sqlite3_close(db);
        return NULL;
    }

    // 创建用户账号表
    char *sql_accounts = "CREATE TABLE IF NOT EXISTS accounts ("
                         "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                         "name TEXT UNIQUE,"
                         "pwd TEXT);";
    rc = sqlite3_exec(db, sql_accounts, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "创建 accounts 表失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        sqlite3_close(db);
        return NULL;
    }

    return db;
}

// 插入客户端连接信息
int ClientData_Insert(sqlite3 *db, ClientData data) {
    char sql[256];
    sprintf(sql, "INSERT INTO clients (sock_fd, name) VALUES (%d, '%s');", 
            data.sock_fd, data.name);
    char *errmsg;
    int rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "插入客户端信息失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    return 0;
}

// 根据 fd 查询昵称
int ClientData_GetNameByFd(sqlite3 *db, int fd, char *name) {
    char sql[256];
    sprintf(sql, "SELECT name FROM clients WHERE sock_fd = %d;", fd);
    char **result;
    int nrow, ncol;
    char *errmsg;
    int rc = sqlite3_get_table(db, sql, &result, &nrow, &ncol, &errmsg);
    if (rc != SQLITE_OK || nrow == 0) {
        if (errmsg) sqlite3_free(errmsg);
        return -1;
    }
    strcpy(name, result[1]);  // 第 0 行是表头，第 1 行是数据
    sqlite3_free_table(result);
    return 0;
}

// 根据昵称查询 fd
int ClientData_GetFdByName(sqlite3 *db, const char *name, int *fd) {
    char sql[256];
    sprintf(sql, "SELECT sock_fd FROM clients WHERE name = '%s';", name);
    char **result;
    int nrow, ncol;
    char *errmsg;
    int rc = sqlite3_get_table(db, sql, &result, &nrow, &ncol, &errmsg);
    if (rc != SQLITE_OK || nrow == 0) {
        if (errmsg) sqlite3_free(errmsg);
        return -1;
    }
    *fd = atoi(result[1]);
    sqlite3_free_table(result);
    return 0;
}

// 根据 fd 删除客户端连接信息
int ClientData_DeleteByFd(sqlite3 *db, int fd) {
    char sql[256];
    sprintf(sql, "DELETE FROM clients WHERE sock_fd = %d;", fd);
    char *errmsg;
    int rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "删除客户端信息失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    return 0;
}

// 获取所有在线客户端的 fd
int ClientData_GetAllFds(sqlite3 *db, int *fds, int max_size) {
    char sql[256] = "SELECT sock_fd FROM clients;";
    char **result;
    int nrow, ncol;
    char *errmsg;
    int rc = sqlite3_get_table(db, sql, &result, &nrow, &ncol, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "查询客户端列表失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -1;
    }

    int count = 0;
    for (int i = 1; i <= nrow && i <= max_size; i++) {
        fds[i-1] = atoi(result[i]);
        count++;
    }
    sqlite3_free_table(result);
    return count;
}

// 注册账号（需校验家庭密钥）
int Account_Register(sqlite3 *db, const char *name, const char *pwd, const char *family_key) {
    // 校验家庭密钥
    if (strcmp(family_key, FAMILY_KEY) != 0) {
        return -1;  // 密钥错误
    }

    // 检查账号是否已存在
    char sql[256];
    sprintf(sql, "SELECT name FROM accounts WHERE name = '%s';", name);
    int exists = 0;
    char *errmsg;
    int rc = sqlite3_exec(db, sql, callback_exists, &exists, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "查询账号失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    if (exists) {
        return -2;  // 账号已存在
    }

    // 插入新账号
    sprintf(sql, "INSERT INTO accounts (name, pwd) VALUES ('%s', '%s');", name, pwd);
    rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "插入账号失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    return 0;  // 注册成功
}

// 登录校验
int Account_Login(sqlite3 *db, const char *name, const char *pwd) {
    char sql[256];
    sprintf(sql, "SELECT pwd FROM accounts WHERE name = '%s';", name);
    char **result;
    int nrow, ncol;
    char *errmsg;
    int rc = sqlite3_get_table(db, sql, &result, &nrow, &ncol, &errmsg);
    if (rc != SQLITE_OK || nrow == 0) {
        if (errmsg) sqlite3_free(errmsg);
        return -1;  // 账号不存在
    }

    if (strcmp(result[1], pwd) != 0) {
        sqlite3_free_table(result);
        return -2;  // 密码错误
    }

    sqlite3_free_table(result);
    return 0;  // 登录成功
}